package br.com.janalise.leitorpdf;


import br.com.janalise.view.SplashJframe;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import org.jpedal.PdfDecoder;
import org.jpedal.exception.PdfException;
import org.jpedal.exception.PdfSecurityException;
import org.jpedal.grouping.PdfGroupingAlgorithms;

import org.jpedal.objects.PdfPageData;
import org.jpedal.utils.LogWriter;
import br.com.janalise.util.RemoverStopList;

public class ExtractTextInRectangle {


  protected String text =null;

  private static boolean useXMLExtraction=false;

  protected static boolean writeToFile=true;

  protected String user_dir = "./";

  public static boolean showMessages=true;

  protected String separator = System.getProperty("file.separator");

  protected PdfDecoder decodePdf = null;

  protected String outputDir = "";

  protected SplashJframe paiFrame;

  protected static int defX1=-1,defX2,defY1,defY2;

//  private static String testFile = "C:/Users/boskyn9/livrosPDF/java.pdfC:/Users/boskyn9/livrosPDF/java.pdf";
  private static String testFile = "http://www.saulo.pro.br/arquivos/Estatistica3.pdf";

  public ExtractTextInRectangle() {
  }

  public ExtractTextInRectangle(String file_name, SplashJframe frame, boolean mensagem) {

      showMessages = mensagem;
      paiFrame = frame;
    String xmlFlag=System.getProperty("xml");
    if(xmlFlag!=null){
      ExtractTextInRectangle.useXMLExtraction=true;
    }

    if (user_dir.endsWith(separator) == false)
      user_dir = user_dir + separator;

    if (file_name.toLowerCase().endsWith(".pdf")) {
      decodeFile(file_name);
    } else {


      String[] files = null;
      File inputFiles = null;

      if (!file_name.endsWith(separator))
        file_name = file_name + separator;

      try {
        inputFiles = new File(file_name);

        if (!inputFiles.isDirectory()) {
          System.err.println(
            file_name + " is not a directory. Exiting program");
        }
        files = inputFiles.list();
      } catch (Exception ee) {
        LogWriter.writeLog(
          "Exception trying to access file " + ee.getMessage());
      }

      long fileCount = files.length;

      for (int i = 0; i < fileCount; i++) {
        if(showMessages)
        System.out.println(i + "/ " + fileCount + ' ' + files[i]);

        if (files[i].toLowerCase().endsWith(".pdf")) {
          if(showMessages)
          System.out.println(file_name + files[i]);

          decodeFile(file_name + files[i]);
        }
      }
    }
  }

  protected void decodeFile(String file_name) {


    String name = "demo"; 

    int pointer = file_name.lastIndexOf(separator);

    if (pointer != -1)
      name = file_name.substring(pointer + 1, file_name.length() - 4);

    outputDir = user_dir + "texto" + separator + name + separator;

    File page_path = new File(outputDir + separator);
            if (!page_path.exists()){
              page_path.mkdirs();               
            }else{
              System.out.println("arquivo já lido...");
              return;
            }
    try {
      decodePdf = new PdfDecoder(false);

      if(!useXMLExtraction)
        PdfDecoder.useTextExtraction();

      decodePdf.setExtractionMode(PdfDecoder.TEXT);

      decodePdf.init(true);

      if(showMessages)
      System.out.println("Opening file :" + file_name);
      decodePdf.openPdfFile(file_name);

    } catch (PdfSecurityException se) {
      System.err.println("Security Exception " + se + " in pdf code for text extraction on file "+decodePdf.getObjectStore().getCurrentFilename());
    } catch (PdfException se) {
      System.err.println("Pdf Exception " + se + " in pdf code for text extraction on file "+decodePdf.getObjectStore().getCurrentFilename());
    } catch (Exception e) {
      System.err.println("Exception " + e + " in pdf code for text extraction on file "+decodePdf.getObjectStore().getCurrentFilename());
      e.printStackTrace();
    }

    if(!decodePdf.isExtractionAllowed()){
            if(showMessages)
        System.out.println("Text extraction not allowed");
   }else if (decodePdf.isEncrypted() && !decodePdf.isPasswordSupplied()) {
      if(showMessages){
        System.out.println("Encrypted settings");
        System.out.println(
          "Please look at SimpleViewer for code sample to handle such files");
        System.out.println("Or get support/consultancy");
      }
    } else {
      int start = 1, end = decodePdf.getPageCount();

      try {
          paiFrame.log.setBounds(0, 340, paiFrame.getX(), 20);
          paiFrame.barLeitor.setMaximum(end);
        for (int page = start; page < end + 1; page++) { //read pages
         
          decodePdf.decodePage(page);

          PdfGroupingAlgorithms currentGrouping = decodePdf.getGroupingObject();

          PdfPageData currentPageData = decodePdf.getPdfPageData();

          int x1,y1,x2,y2;

          if(defX1==-1){
            x1 = currentPageData.getMediaBoxX(page);
            x2 = currentPageData.getMediaBoxWidth(page)+x1;

            y2 = currentPageData.getMediaBoxY(page);
            y1 = currentPageData.getMediaBoxHeight(page)+y2;
          }else{
            x1=defX1;
            y1=defY1;
            x2=defX2;
            y2=defY2;
          }

          if(showMessages)
//          System.out.println(
//            "Extracting text from rectangle ("
//              + x1
//              + ','
//                                + y1
//              + ' '
//                                + x2
//              + ','
//                                + y2
//              + ')');

          text =null;


          try{
            text =currentGrouping.extractTextInRectangle(
              x1,
              y1,
              x2,
              y2,
              page,
              false,
              true);
          } catch (PdfException e) {
            decodePdf.closePdfFile();
            System.err.println("Exception " + e.getMessage()+" in file "+decodePdf.getObjectStore().fullFileName);
            e.printStackTrace();
          }

          if (text == null) {
            if(showMessages)
            System.out.println("No text found");
          } else if(writeToFile){          

            String prefix=".txt";
            String encoding=System.getProperty("file.encoding");

            if(useXMLExtraction){
              prefix=".xml";
              encoding="UTF-8";
            }

            if(showMessages){
                paiFrame.log.setText("lendo página "+page+" de "+end);
                paiFrame.barLeitor.setValue(paiFrame.barLeitor.getValue()+1);
                if(paiFrame.barLeitor.getValue()==end)
                    paiFrame.barLeitor.setValue(0);
            }
            OutputStreamWriter output_stream =
              new OutputStreamWriter(
                new FileOutputStream(outputDir + "texto" + prefix,true),
                encoding);
            
            if((useXMLExtraction)){
              output_stream.write(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
              output_stream.write(
                "<!-- Pixel Location of text x1,y1,x2,y2\n");
              output_stream.write("(x1,y1 is top left corner)\n");
              output_stream.write("(x1,y1 is bottom right corner)\n");
              output_stream.write(
                "(origin is bottom left corner)  -->\n");
              output_stream.write("\n\n<ARTICLE>\n");
              output_stream.write(
                "<LOCATION x1=\""
                  + x1
                  + "\" "
                  + "y1=\""
                  + y1
                  + "\" "
                  + "x2=\""
                  + x2
                  + "\" "
                  + "y2=\""
                  + y2
                  + "\" />\n");
              output_stream.write("\n\n<TEXT>\n");
              output_stream.write(text); 
              output_stream.write("\n\n</TEXT>\n");
              output_stream.write("\n\n</ARTICLE>\n");
            }else
              output_stream.write(text); 

            output_stream.close();
          }

          decodePdf.flushObjectValues(false);
        }
      } catch (Exception e) {
        decodePdf.closePdfFile();
        System.err.println("Exception " + e.getMessage());
        e.printStackTrace();
        System.out.println(decodePdf.getObjectStore().getCurrentFilename());
      }
      decodePdf.flushObjectValues(true);

      if(showMessages)
      System.out.println("Text read");

    }

    decodePdf.closePdfFile();

  }
  public static void main(String[] args) {

    if(showMessages)
    System.out.println("Simple demo to extract text objects");

    String file_name = testFile;


    if(args.length==5){

      file_name = args[0];
      System.out.println("File :" + file_name);

      System.out.println("User coordinates supplied");
      defX1=Integer.parseInt(args[1]);
      defY1=Integer.parseInt(args[2]);
      defX2=Integer.parseInt(args[3]);
      defY2=Integer.parseInt(args[4]);
    }else{
      System.out.println("Please call with either ");
      System.out.println("FileName");
      System.out.println("or");
      System.out.println("FileName x1 y1 x2 y2");
    }

    File pdf_file = new File(file_name);

    if (pdf_file.exists() == false) {
      System.out.println("File " + file_name + " not found");
    }
    long now=System.currentTimeMillis();
    new ExtractTextInRectangle(file_name,null,false);
    long finished=System.currentTimeMillis();

    
    System.out.println("Time taken="+((finished-now)/1000));

  }

  public String getExtractedText() {
    return text;
  }
}
